package com.example.konwRice.Dao;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.example.konwRice.DB.DBCreater;
import com.example.konwRice.domain.item;

import java.util.ArrayList;

/**
 * @Author: Stars
 */
public class HistoryDao {
    private DBCreater dbCreater;

    public HistoryDao(Context context) {
        dbCreater = new DBCreater(context, DBCreater.DATABASE_NAME, null, DBCreater.DATABASE_VERSION);
    }

    public void insertHistory(item items) {
        SQLiteDatabase db = dbCreater.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("title", items.getTitle());
        values.put("url", items.getUrl());
        values.put("imageUrl", items.getImageId());
        db.insert("history", null, values);
    }

    @SuppressLint("Range")
    public ArrayList<item> queryHistory() {
        ArrayList<item> items = new ArrayList<item>();

        SQLiteDatabase db = dbCreater.getReadableDatabase();

        Cursor cursor = db.query("history", null, null, null, null, null, null, null);

        if (cursor.moveToFirst()) {
            do {
                item newsItem = new item();
                newsItem.setTitle(cursor.getInt(cursor.getColumnIndex("title")));
                newsItem.setUrl(cursor.getString(cursor.getColumnIndex("url")));
                newsItem.setImageId(cursor.getInt(cursor.getColumnIndex("imageUrl")));
                items.add(newsItem);
            } while (cursor.moveToNext());
        }
        return items;
    }
    @SuppressLint("Range")
    public ArrayList<item> Search(String str){
        ArrayList<item> items =new ArrayList<item>();
        SQLiteDatabase db = dbCreater.getReadableDatabase();
        Cursor cursor = db.query("history", null, "title like '%"+str+"%'", null, null, null, null, null);
        if (cursor.moveToFirst()) {
            do {
                item newsItem = new item();
                newsItem.setTitle(cursor.getInt(cursor.getColumnIndex("title")));
                newsItem.setUrl(cursor.getString(cursor.getColumnIndex("url")));
                newsItem.setImageId(cursor.getInt(cursor.getColumnIndex("imageUrl")));
                items.add(newsItem);
            } while (cursor.moveToNext());
        }
        return items;
    }

}
